import config from '../config';


function request_notification() {
  if (Notification && Notification.permission !== "granted") {
    Notification.requestPermission((status) => {
      console.log("notification permission " + status);
    });
  }
  console.log("notification status: ", Notification.permission);
}

function NewNotification(title, options) {
  let notify = new Notification(title, options);
  notify.onshow = () => {};
  notify.onclick = () => {};
  notify.onclose = () => {};
  notify.onerror = () => {};
}

function get_url(email, access_token) {
  let protocol = window.location.protocol === "http:" ? "ws://" : "wss://";
  let url = protocol + window.location.host + "/api/v1/notification/?email=" + email + "&access_token=" + access_token;
  return url;
}

function on_notification(data) {
  if(!!!data.method) {
    console.log("recv data, but format error.");
    return;
  }
  let title = "";
  if(data.method === "REGISTER") {
    title += "设备上线通知";
  } else if(data.method === "UPLOAD") {
    title += "数据上报通知";
  } else if(data.method === "DATACK") {
    title += "设备数据确认通知";
  } else {
    title += "未知通知格式 "
  }
  title += " " + new Date().toLocaleString();

  let body = "设备: " + data.imei;
  if(data.data) {
    body += "\n" + "数据:" + data.data;
  }

  let img_url = window.location.protocol + "//" + window.location.host;
  img_url += process.env.NODE_ENV === 'production' ? config.build.assetsPublicPath : config.dev.assetsPublicPath;
  img_url += img_url.endsWith("/") ? "" : "/";
  img_url += "static/img/notify.png";
  NewNotification(title, {
    lang: "utf-8",
    icon: img_url,
    body: body
  });
}

export default {
  install: (Vue, options) => {
    let wsconn = null;

    request_notification();
    Vue.prototype.open_notification = (email, access_token) => {
      let url = get_url(email, access_token);
      console.log('connect to ws url ' + url);
      wsconn = new WebSocket(url);

      wsconn.onopen = (evt) => {
        console.log("OPENED.");
      }
      wsconn.onclose = (evt) => {
        console.log("CLOSED.");
      }
      wsconn.onmessage = (evt) => {
        console.log(evt.data);
        on_notification(JSON.parse(evt.data));
      }
      wsconn.onerror = (evt) => {
        console.log("ERROR OCCURED.");
      }
    };
    Vue.prototype.close_notification = () => {
      if (!!wsconn) {
        wsconn.close();
      }
    };
    Vue.prototype.send_notification = (msg) => {
      if (!!wsconn) {
        wsconn.send(msg);
      }
    };
  }
}
